package com.yenroc.ho.service;

import com.yenroc.ho.annotation.GlobalTransaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class GoodsService {

    private Logger log = LoggerFactory.getLogger(GoodsService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GlobalTransaction
    public Map<String, Object> reduceGood(Map<String, Object> params){
        log.info("进行库存减少.." + params);
        Integer goodId = (Integer) params.get("goodId");
        Integer payNum = (Integer) params.get("payNum");

        Map<String, Object> stringObjectMap = jdbcTemplate.queryForMap("select num from tk_goods where id = ?", goodId);
        if (stringObjectMap.size() ==
                0 || Integer.parseInt(stringObjectMap.get("num").toString())< payNum) {
            throw new RuntimeException("库存不足");
        }

        int update = jdbcTemplate.update("update tk_goods set num = num-? where id = ?",payNum, goodId);
        log.info("商品=[{}],减少=[{}],受影响=[{}]行", goodId, payNum, update);
        Map<String, Object> result = new HashMap<>();
        result.put("result", update);
        return result;
    }
}
